﻿// copyright jyz.2024

#include "AuraProjectile.h"

#include "AbilitySystemBlueprintLibrary.h"
#include "AbilitySystemComponent.h"
#include "AuraRPGDemo.h"
#include "NiagaraFunctionLibrary.h"
#include "Components/AudioComponent.h"
#include "Components/SphereComponent.h"
#include "GameFramework/ProjectileMovementComponent.h"
#include "Kismet/GameplayStatics.h"

AAuraProjectile::AAuraProjectile()
{
	PrimaryActorTick.bCanEverTick = false;
	SphereComponent = CreateDefaultSubobject<USphereComponent>("SphereComponent");
	SetRootComponent(SphereComponent);
	SphereComponent->SetCollisionEnabled(ECollisionEnabled::QueryOnly);
	SphereComponent->SetCollisionResponseToAllChannels(ECR_Ignore);
	SphereComponent->SetCollisionResponseToChannel(ECC_WorldDynamic,ECR_Overlap);
	SphereComponent->SetCollisionResponseToChannel(ECC_Visibility,ECR_Overlap);
	SphereComponent->SetCollisionResponseToChannel(ECC_Pawn,ECR_Overlap);
	SphereComponent->SetCollisionObjectType(ECC_Projectile);
	ProjectileMovementComp = CreateDefaultSubobject<UProjectileMovementComponent>("ProjectileMovementComp");
	ProjectileMovementComp->InitialSpeed = 550.f;
	ProjectileMovementComp->MaxSpeed = 550.f;
	ProjectileMovementComp->ProjectileGravityScale = 0.f;
	//开启网络同步
	bReplicates = true;
}

void AAuraProjectile::BeginPlay()
{
	Super::BeginPlay();
	SphereComponent->OnComponentBeginOverlap.AddDynamic(this,&AAuraProjectile::OnSphereOverlap);
	AudioComponent = UGameplayStatics::SpawnSoundAttached(LoopSound,GetRootComponent());
	SetLifeSpan(LifeSpanTime);
}

void AAuraProjectile::Destroyed()
{
	Super::Destroyed();
	//只适用于客户端
	if(!bHit && ! HasAuthority())
	{
		UGameplayStatics::PlaySoundAtLocation(
			this,ImpactSound,GetActorLocation(),FRotator::ZeroRotator);

		UNiagaraFunctionLibrary::SpawnSystemAtLocation(this,ImpactEffect,GetActorLocation());
		AudioComponent->Stop();
	}
}

void AAuraProjectile::OnSphereOverlap(
		UPrimitiveComponent* OverlappedComponent,
		AActor* OtherActor, 
		UPrimitiveComponent* OtherComp, 
		int32 OtherBodyIndex,
		bool bFromSweep,
		const FHitResult& SweepResult)
{
	UGameplayStatics::PlaySoundAtLocation(
		this,ImpactSound,GetActorLocation(),FRotator::ZeroRotator);

	UNiagaraFunctionLibrary::SpawnSystemAtLocation(this,ImpactEffect,GetActorLocation());
	if(AudioComponent)
		AudioComponent->Stop();
	if(HasAuthority())
	{
		if(UAbilitySystemComponent*TargetASC = UAbilitySystemBlueprintLibrary::GetAbilitySystemComponent(OtherActor))
		{
			TargetASC->ApplyGameplayEffectSpecToSelf(*DamageEffectSpecHandle.Data.Get()/*,TargetASC->ScopedPredictionKey*/);
		}
	
		Destroy();
	}
	else
	{
		bHit = true;
	}
}
